package laji;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class MainWindow extends JFrame {
    private JPanel contentPane;
    private JList<String> blogList;
    private DefaultListModel<String> blogListModel;

    private JButton addButton;
    private JButton viewButton;

    private List<Blog1> blogs;

    public MainWindow() {
        setTitle("博客系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 300));
        pack();
        setLocationRelativeTo(null);

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 10));

        blogListModel = new DefaultListModel<>();
        blogList = new JList<>(blogListModel);
        JScrollPane scrollPane = new JScrollPane(blogList);
        contentPane.add(scrollPane, BorderLayout.CENTER);

        addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                openBlogEditorWindow();
            }
        });
        contentPane.add(addButton, BorderLayout.SOUTH);

        viewButton = new JButton("查看");
        viewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int selectedIndex = blogList.getSelectedIndex();
                if (selectedIndex != -1) {
                    openBlogViewerWindow(selectedIndex);
                } else {
                    JOptionPane.showMessageDialog(MainWindow.this, "请选择一篇博客");
                }
            }
        });
        contentPane.add(viewButton, BorderLayout.NORTH);

        blogs = new ArrayList<>();
        blogs.add(new Blog1("1","11","aa"));
        blogs.add(new Blog1("1","11","aa"));
        blogs.add(new Blog1("1","11","aa"));

        updateBlogList();
    }

    private void updateBlogList() {
        blogListModel.clear();
        for (Blog1 blog : blogs) {
            blogListModel.addElement(blog.getTitle());
        }
    }

    private void openBlogEditorWindow() {
        BlogEditorWindow editorWindow = new BlogEditorWindow(this);
        editorWindow.setVisible(true);
    }

    private void openBlogViewerWindow(int selectedIndex) {
        BlogViewerWindow viewerWindow = new BlogViewerWindow(blogs.get(selectedIndex));
        viewerWindow.setVisible(true);
    }

    public void addBlog(Blog1 blog) {
        blogs.add(blog);
        updateBlogList();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MainWindow mainWindow = new MainWindow();
                mainWindow.setVisible(true);
            }
        });
    }
}
